//standard settings
var lat=59.9138204;
var lon=10.7387413;
var zoom=15;
var lonLat;

//map object
var map;

//layer objects
var layerGPSMarkers;
var layerGeoMarkers;

//icon
var gpsMarkerIcon;
var sizeGps;
var offsetGps;

//html elements
var divDrop;
var gpsMenu;
var divBack;
var markerMenu;

//markers
var gpsMarker; 

var navMode = false;

//timer for waypoint updating
var timer;

//array of waypoints from server
var locations;

//Initialise the 'map' object
function init() {

	//binds handler to html element
	divDrop = $('dropDown');
	divBack = $('fadeDiv');
	markerMenu = $('markerMenu');

	//create map
	map = new OpenLayers.Map ("map", {
                controls:[
                    new OpenLayers.Control.Navigation(),
                    new OpenLayers.Control.Attribution()],
                maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34),
                maxResolution: 156543.0399,
                numZoomLevels: 19,
                units: 'm',
                projection: new OpenLayers.Projection("EPSG:900913"),
                displayProjection: new OpenLayers.Projection("EPSG:4326")
        } );

	//create icons
	sizeGps = new OpenLayers.Size(15,15);
	offsetGps = new OpenLayers.Pixel(-(sizeGps.w/2), -sizeGps.h);
	gpsMarkerIcon = new OpenLayers.Icon('red_dot.png', sizeGps, offsetGps);	

        // Define the map layer
	layerTilesAtHome = new OpenLayers.Layer.OSM.Osmarender("Osmarender");
  	map.addLayer(layerTilesAtHome);
	
	//Define the marker layer	
	layerGPSMarkers = new OpenLayers.Layer.Markers("GPS_Markers");
	map.addLayer(layerGPSMarkers);
	layerGeoMarkers = new OpenLayers.Layer.Markers("Geo_Markers");
	map.addLayer(layerGeoMarkers);

 	if(!map.getCenter()){
		lonLat = new OpenLayers.LonLat(lon, lat).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
		map.setCenter(lonLat, zoom);	
	}        

	//create marker
	gpsMarker = new OpenLayers.Marker(lonLat, gpsMarkerIcon);
	layerGPSMarkers.addMarker(gpsMarker);

	//Setting up connection to GPS, using signal and slot via webkit	
	try {
    		pos.positionChanged.connect(slot);
  	}
  	catch(e) {
    		//alert("No support for GPS");
  	}

	//disable text and image selection, since the text is buttons
  	//document.onmousedown = function() {return false;}

	//events
	map.events.register( 'moveend', this, navMarker);
	map.events.register( 'click', this, clickMarker);
	
	//load waypoints from server
	updatePos();

	//hotkeys for zoom
	Hotkeys.bind("i", zoomIn);
	Hotkeys.bind("o", zoomOut);
}

//draw waypoints in locations on the map
function addGeoPositions(){
	layerGeoMarkers.clearMarkers();

	for(var i=0; i<locations.length; i++){
		var tmpLonLat = new OpenLayers.LonLat(locations[i].longitude, locations[i].latitude)
		.transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
		var tmpDesc = "";		
		if(zoom > 10){
			tmpDesc = locations[i].description;	
		}

		layerGeoMarkers.addMarker(new OpenLayers.Marker.Label(tmpLonLat,null,tmpDesc));	
	}
	timer = setTimeout('updatePos()',120000);
}

//get all waypoints from the server
function updatePos(){
	new Ajax.Request('http://okvamme.com/qtserver/index.php/api/getmarkers',
  	{
    		method:'get',
    		onSuccess: function(transport){
			//replace waypoints with waypoints from server
      			locations = transport.responseText.evalJSON();
      			addGeoPositions();
    		},
    		onFailure: function(){ 
			alert('Problem with connecting to location server.'); 
			timer = setTimeout('updatePos()',60000);
		}
  	});
}

//adds new waypoint on the server
function sendPos(){
	clearTimeout(timer);
	var tmpLonLat = map.getCenter().transform(map.getProjectionObject(), new OpenLayers.Projection("EPSG:4326"));
	var desc = $('desc').value;
	$('desc').value = "";

	new Ajax.Request('http://okvamme.com/qtserver/index.php/api/setmarker',
  	{
    		method:'post',
		parameters: { lat:tmpLonLat.lat, lon:tmpLonLat.lon, desc:desc},
    		onSuccess: function(transport){
      			updatePos();
    		},
    		onFailure: function(){ 
			alert('Problem with connecting to location server.'); 
		}
  	});	
}

//connection between GPS
function slot(object){
	set_pos(object.latitude, object.longitude);
}
    
function set_pos(lati, longi){
	lat = lati;
	lon = longi;
        if(!navMode){
		lonLat = new OpenLayers.LonLat(lon, lat).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
		map.events.unregister( 'moveend', this, navMarker);		
		map.setCenter (lonLat);
		gpsMarker = new OpenLayers.Marker(lonLat, gpsMarkerIcon);
		layerGPSMarkers.addMarker(gpsMarker);
		map.events.register( 'moveend', this, navMarker);
	}
}

function navMarker(evt){
	navMode = true;
	lonLat = map.getCenter();
	gpsMarker = new OpenLayers.Marker(lonLat, gpsMarkerIcon);
	layerGPSMarkers.addMarker(gpsMarker);
}

function clickMarker(evt){
	navMode = true;
	map.events.unregister( 'moveend', this, navMarker);
 	lonLat = map.getLonLatFromViewPortPx(new OpenLayers.Pixel(evt.xy.x , evt.xy.y));
	map.setCenter(lonLat);
	gpsMarker = new OpenLayers.Marker(lonLat, gpsMarkerIcon);
	layerGPSMarkers.addMarker(gpsMarker);
	map.events.register( 'moveend', this, navMarker);	
}

function zoomIn(){
	if(zoom < 17){
		zoom++;		
		map.setCenter(map.getCenter(), zoom);
		addGeoPositions()
	}
}

function zoomOut(){
	if(zoom > 0){
		zoom--;
		map.setCenter(map.getCenter(), zoom);
		addGeoPositions()
	}
}

function menu(){
	divDrop.style.visibility = "visible";
	divBack.style.visibility = "visible";
	cancelWaypoint();
	gpsMenu = document.getElementById("gps");
	GpsMenuColor();	
}

function removeMenu(){
	divDrop.style.visibility = "hidden";
	divBack.style.visibility = "hidden";
}

function GpsMenuColor(){
	if(!navMode){		
		gpsMenu.style.backgroundColor = "yellow";
		gpsMenu.style.color = "black";
	}else{
		gpsMenu.style.backgroundColor = "black"
		gpsMenu.style.color = "white";
	}
}

function addWaypoint(){
	removeMenu();
	markerMenu.style.visibility = "visible";
}

function sendWaypoint(){
	markerMenu.style.visibility = "hidden";
	sendPos();
}

function cancelWaypoint(){
	markerMenu.style.visibility = "hidden";
	$('desc').value = "";
}

function toggleGPS(){
	navMode = !navMode;
	removeMenu();
	GpsMenuColor();
}

function oslo(){
	removeMenu();
	lat=59.9138204;
	lon=10.7387413;
	zoom = 15;
	lonLat = new OpenLayers.LonLat(lon, lat).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
	map.events.unregister( 'moveend', this, navMarker);		
	map.setCenter (lonLat, zoom);
	gpsMarker = new OpenLayers.Marker(lonLat, gpsMarkerIcon);
	layerGPSMarkers.addMarker(gpsMarker);
	map.events.register( 'moveend', this, navMarker);
	navMode = true;
}
